﻿using System;
using System.Collections.Generic;
using PetaPoco;
using doufu.Common;
using doufu.Model;

namespace doufu.Service
{
    public class StoryService
    {
        public Page<story> Pager(int? page)
        {
            return CommonDac.Query(db => db.Page<story>(page, 20, "select * from story order by id desc"));
        }
        public Page<story> Pager(int? page, int categoryId)
        {
            return CommonDac.Query(db => db.Page<story>(page, 20, "select * from story where story_category=@categoryId order by id desc", new { categoryId }));
        }

        public story Detail(int id)
        {
            return CommonDac.Query(db => db.FirstOrDefault<story>("select * from story where id=@0", id));
        }

        public story Detail(Guid guid)
        {
            return CommonDac.Query(db =>
            {
                var details = db.FirstOrDefault<storyDetails>(@"select story.*,category.category_name,users.user_name created_by_name from story
                                left join category on category.category_id=story.story_category
                                left join users on story.created_by=users.user_id
                                 where guid=@0", guid);
                if (details != null)
                {
                    if (details.created_at == DateTime.MinValue)
                    {
                        details.created_at = DateTime.Now;
                    }
                    if (details.modified_at == DateTime.MinValue)
                    {
                        details.modified_at = DateTime.Now;
                    }
                    details.click += 1;
                    db.Update(details, new List<string> { "click" });
                }
                return details;
            });
        }

        [UserAuthorize]
        public bool Save(story entity, IUser user)
        {
            return CommonDac.Query(db =>
                 {
                     entity.modified_at = DateTime.Now;
                     entity.modified_by = user.user.UserId;
                     if (entity.created_by == 0)
                     {
                         entity.created_by = entity.modified_by;
                     }
                     if (entity.id == 0)
                     {
                         entity.guid = Guid.NewGuid();
                         entity.created_at = DateTime.Now;
                         entity.modified_at = DateTime.Now;
                         db.Insert(entity);
                     }
                     else
                     {
                         entity.modified_at = DateTime.Now;
                         db.Update(entity, new List<string> { "story_title", "story_content", "story_category", "story_seo", "modified_at", "modified_by" });
                     }
                     return true;
                 });
        }
    }
}